package com.ledi.guns.config;

import javax.servlet.Filter;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.ledi.guns.core.util.baiduUtil.ActionEnter;
import com.ledi.guns.core.util.baiduUtil.ConfigManager;
import com.ledi.guns.core.util.baiduUtil.UEditorConfig;

/**
 * Created by pangxiaofeng on 2017/6/17.
 */
@Configuration
@EnableConfigurationProperties(UEditorConfig.class)
public class WebMvcConfiguration extends WebMvcConfigurerAdapter {

	@Autowired
	private UEditorConfig uEditorConfig;

	@Bean
	@ConditionalOnMissingBean(ActionEnter.class)
	public ActionEnter actionEnter() {

		ActionEnter actionEnter = new ActionEnter(ConfigManager.getInstance(uEditorConfig));
		return actionEnter;
	}

	@Bean
	public CorsFilter corsFilter() {

		final UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
		final CorsConfiguration corsConfiguration = new CorsConfiguration();
		corsConfiguration.setAllowCredentials(true);
		corsConfiguration.addAllowedOrigin("*");
		corsConfiguration.addAllowedHeader("*");
		corsConfiguration.addAllowedMethod("*");
		urlBasedCorsConfigurationSource.registerCorsConfiguration("/**", corsConfiguration);
		return new CorsFilter(urlBasedCorsConfigurationSource);
	}

	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {

		registry.addResourceHandler("/upload/**").addResourceLocations("file:" + uEditorConfig.getUploadPath());
		super.addResourceHandlers(registry);
	}

	/**
	 * 用于处理编码问题
	 *
	 * @return
	 */
	@Bean
	public Filter characterEncodingFilter() {

		CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
		characterEncodingFilter.setEncoding("UTF-8");
		characterEncodingFilter.setForceEncoding(true);
		return characterEncodingFilter;
	}

}
